//
//  FYRefreshControl.swift
//  Mircore
//
//  Created by apple on 16/8/14.
//  Copyright © 2016年 飞羽. All rights reserved.
//

import UIKit


//当前视图的高度

private let  FYRefreshControlHeight: CGFloat  = 50

//刷新状态

enum FYRefreshControlType: Int {
    
    //下拉刷新
    case Normal = 0
    
    //将要刷新
    case Pulling = 1
    
    //正在刷新
    case Refreshing = 2
}

//自定义下拉刷新控件

class FYRefreshControl: UIControl {

    //当前滚动的视图
    
    var  currentScrollView: UIScrollView?
    
    
    //当前的状态
    
    var  refreshState: FYRefreshControlType = .Normal {
    
        didSet {
        
            switch refreshState {
            case .Normal:
                
                //显示文字为下拉刷新
                messageLabel.text  = "下拉刷新"
                
                //风火轮
                
                indicatorView.stopAnimating()
                
                //箭头显示  箭头重置
                
                iconImageView.hidden  = false
                
                UIView.animateWithDuration(0.25, animations: { 
                    
                    self.iconImageView.transform =  CGAffineTransformIdentity
                })
                
                //刷新完成回到默认位置  前提上一次请求是正在刷新状态
                
                //oldValue  获取上一次的存储的数据是正在刷新然后我们在对contentInset.top 减去一个自身的高度
                
                if  oldValue == .Refreshing {
                
                 UIView.animateWithDuration(0.25, animations: { 
                    
                    self.currentScrollView?.contentInset.top  -= FYRefreshControlHeight
                 })
                
                }
                
            case.Pulling:
                
                messageLabel.text  = "松手就刷新"
                
                //下拉箭头调转
                UIView.animateWithDuration(0.25, animations: { 
                    
                    self.iconImageView.transform =  CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                
            case.Refreshing:
                
                //显示文字为正在刷新
                
                messageLabel.text = "正在刷新"
                
                //下拉箭头隐藏  开启风火轮
                
                iconImageView.hidden  = true
                
                indicatorView.startAnimating()
                
                //设置停留位置
                
                UIView.animateWithDuration(0.25, animations: { 
                    
                    //一定要记住
                    
                    self.currentScrollView?.contentInset.top  +=  FYRefreshControlHeight
                })
           //发送通知(一定要记住)
        
                sendActionsForControlEvents(.ValueChanged)
        }
    
    }
    
    }
    //MARK:-  懒加载控件
    
    
    private  lazy  var  iconImageView: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    
    //风火轮
    
    private  lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
    
    
    //显示文案
    
    private lazy  var messageLabel: UILabel = {
    
     let label  = UILabel()
        
        label.font  = UIFont.systemFontOfSize(12)
        
        label.textColor = UIColor.grayColor()
        
        label.text  = "下拉刷新"
    
       return label
    }()
    
    
    override  init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        
        fatalError("init(coder:) has not been implemented")
    }
    
    //添加控件设置约束
    
    private  func  setupUI() {
    
    
    backgroundColor  = UIColor.redColor()
    
    
        //添加控件
        
        addSubview(iconImageView)
        
        addSubview(indicatorView)
        
        addSubview(messageLabel)
        
        
        
        //使用系统约束
        
        iconImageView.translatesAutoresizingMaskIntoConstraints  = false
        
        indicatorView.translatesAutoresizingMaskIntoConstraints = false
        
        messageLabel.translatesAutoresizingMaskIntoConstraints = false
        
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1, constant: -35))
        
        addConstraint(NSLayoutConstraint(item: iconImageView, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterX, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterX, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: indicatorView, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .Leading, relatedBy: .Equal, toItem: iconImageView, attribute: .Trailing, multiplier: 1, constant: 0))
        
        addConstraint(NSLayoutConstraint(item: messageLabel, attribute: .CenterY, relatedBy: .Equal, toItem: iconImageView, attribute: .CenterY, multiplier: 1, constant: 0))
        
        
    }
    
    //监听tableview的滚动  拿到tableview  将控件将要添加到那个父亲视图上
    
    override  func  willMoveToSuperview(newSuperview: UIView?) {
        
        //判断父视图是否是可以滚动的视图
        
        guard  let  scrollView = newSuperview  as? UIScrollView  else  {
        
          return
        }
        
        //代码执行到此是滚动的视图
        
        //设置视图的frame
        
        self.frame.size.width  = scrollView.frame.size.width
        
        self.frame.size.height  = FYRefreshControlHeight
        
        self.frame.origin.y = -FYRefreshControlHeight
        
        
        //KVO监听滚动对象contentOFFSet属性的改变
        
        //监听contentOffset新值的改变
        
        scrollView.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        
        //记录滚动的视图
        
        currentScrollView  = scrollView
    }
    
    //KVO方法
    
    override  func  observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        guard  let  scrollView = currentScrollView  else  {
        
        
          return
            
        }
        
        //获取滚动的y轴的偏移量
        
        let  contentOffSetY  = scrollView.contentOffset.y
        
        
        //计算临界点
        
        let  maxY = -(scrollView.contentInset.top  + FYRefreshControlHeight)
        
        //判断是否在拖动
        
        if  scrollView.dragging  {
        
            if  contentOffSetY < maxY  &&  refreshState  == .Normal  {
            
            refreshState  = .Pulling
            
            }else  if  contentOffSetY >= maxY  && refreshState == .Pulling  {
            
            
              refreshState  = .Normal
            }
        
        }else  {
        
        
            //判断是否进入正在刷新的状态
            
            if refreshState == .Pulling  {
            
            refreshState  = .Refreshing
            }
        }
    }
    
    
    //结束刷新
    func  endRefreshing() {
     
        //进入默认状态
        
        refreshState  = .Normal
    
    }
    
    deinit  {
    
    //移除KVO 
        
        currentScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    
    }

 }





